package com.haoxuewa.config.intercepors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haoxuewa.dao.UserDao;
import com.haoxuewa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/*
 * 登录拦截器
 * */
@Component
public class LoginIntercepor implements HandlerInterceptor {
    private final UserDao userDao;

    @Autowired
    public LoginIntercepor(UserDao userDao) {
        this.userDao = userDao;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //管理员业务的拦截
        String url = request.getRequestURL().toString();
        if (url.contains("adminLogin")) {
            return true;   //管理员请求登录接口就放行
        } else {
            if (request.getSession().getAttribute("SYSTEM_ADMIN_SESSION") != null) {
                return true;   //访问后台的接口查询会话session是否为空
            } else if (url.contains("backstage")) {
                response.sendRedirect(request.getContextPath() + "/manager_login");  //如果会话无效且请求后台接口，就重定向到后台登录页面
            }
        }

        //用户业务的拦截
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            // 重定向到登录页面
            return false;
        }
        // 定义一个userName变量记录浏览器cookie值
        //cookie_username  是服务器发送给浏览器的一个cookie
        String cookie_username = null;
        for (Cookie cookie : cookies) {
            if ("cookie_username".equals(cookie.getName())) {
                cookie_username = cookie.getValue();
                break;
            }
        }

        if (StringUtils.isEmpty(cookie_username)) {
//            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        HttpSession session = request.getSession();
        Object object = session.getAttribute("SYSTEM_USER_SESSION");
        if (Objects.isNull(object)) {
            //select id,name,password,ifnull(gender,'未知') gender,ifnull(birthday,'未知') birthday,email from user where name = #{userName}
            User user = userDao.selectOne(new QueryWrapper<User>().select("id", "name", "password").eq("name", cookie_username));
            session.setAttribute("SYSTEM_USER_SESSION", user);
        }
        //已经登录了
        return true;
    }
}